# encoding: utf-8

import wsgiref.handlers
import os
import re
import cgi
import datetime
import sys

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from templatetags import *

import webstart as webstart
import codecs
import models
import functions
import cache
from models import filesystem

#import options

#def requires_admin(func):
#    def _wrapper(self, *args, **kwargs):   
#        options = functions.get_options()
#        if not users.get_current_user():
#            self.redirect(users.create_login_url(self.request.uri))
#            return
#        elif options.permission.count(users.get_current_user().email()) == 0 and (not users.is_current_user_admin()):
#            self.redirect('/')
#            return 
#        else:
#            return func(self, *args, **kwargs)   
#    return _wrapper
def requires_admin(level): 
    def decorator(func): 
        def wrapper(self,*args, **kwargs):          
#            if level =="admin" :
#                if (not users.is_current_user_admin()):   
#                    self.redirect(users.create_login_url(self.request.uri))
#                    return
#                else:
#                    func(self, *args, **kwargs)
#            else:
#                if not users.get_current_user():
#                    self.redirect(users.create_login_url(self.request.uri))
#                    return
#                elif options.permission.count(users.get_current_user().email()) == 0 and (not users.is_current_user_admin()):
#                    self.redirect('/')
#                    return 
#                else:
#                    return func(self, *args, **kwargs)
#            if level =="admin" :
#                if (users.level > 8):   
#                    func(self, *args, **kwargs)
#                else:
#                    self.redirect(users.create_login_url(self.request.uri))
#                    return
#            else:
            if (users.level >= level):
                return func(self, *args, **kwargs)
            else:
                if not users.get_current_user():
                    self.redirect(users.create_login_url(self.request.uri))
                    return
                else:
                    self.redirect('/')
                    return
        return wrapper 
    return decorator
    
class BaseRequestHandler(webapp.RequestHandler):
    """Supplies a common template generation function.
    
    When you call generate(), we augment the template variables supplied with
    the current user in the 'user' variable and the current webapp request
    in the 'request' variable.
    """
#    def __init__(self):
#        AUTHORS = ['test@example.com','yuping322@gmail.com']
#        
#        self.user = users.get_current_user()
#        if not self.user:
#            return self.redirect(users.create_login_url(self.request.uri))
#        if AUTHORS.count(self.user.email()) == 0 and (not users.is_current_user_admin()):
#            return self.redirect('/')

    def generate(self, template_name, template_values={}):
#        AUTHORS = ['test@example.com','yuping322@gmail.com']
        options = functions.get_options()
#        self.user = users.get_current_user()
#        if not self.user:
#            return self.redirect(users.create_login_url(self.request.uri))
#        if AUTHORS.count(self.user.email()) == 0 and (not users.is_current_user_admin()):
#            return self.redirect('/')
        webapp.template.register_template_library('templatetags.filter')
        values = {
            'request': self.request,
            'user': users.GetCurrentUser(),
            'login_url': users.CreateLoginURL(self.request.uri),
            'logout_url': users.CreateLogoutURL('http://' + self.request.host + '/'),
            'options': options,
        }
        values.update(template_values)
        directory = os.path.dirname(__file__)
        path = os.path.join(directory, os.path.join('templates/admin', template_name))
        self.response.headers["Content-Type"] = "text/html"
        self.response.out.write(template.render(path, values, debug=options.DEBUG))
    
    def generate_js(self, html):
        self.response.headers["Content-Type"] = "text/html"
        self.response.out.write('<script language="JavaScript">'+ html + '</script>')
    
    def generate_js_error(self,title='Error',text=''):
        self.generate_js("Growl.Error({title:'%s', text: '%s'});" % (title,text))
    
    def generate_js_action(self,title='Action',text='',extra=''):
        self.generate_js("Growl.Action({title:'%s', text: '%s'});%s" % (title,text,extra)) 

    def param(self, name, **kw):
        return self.request.get(name, **kw)
    
    def update_archive(self,post,value,new):
        if new == "new":
            des = post.modified.strftime('%Y-%m')
        elif new == "edit":
            src = post.modified.strftime('%Y-%m')
            des = value.strftime('%Y-%m') # May-2008
            if src == des:
                return
        elif new == "del":
            src = post.modified.strftime('%Y-%m')
        else:
            return
        if new == "new" or new == "edit":
            archive = models.Archive.all().filter('yearmonth',des).fetch(10)
                # add to archive
            if archive == []: # new month
                archive = models.Archive(yearmonth=des)
            else: 
                archive = archive[0]
            archive.entrycount += 1
            archive.put()
        if new == "edit" or new == "del":
            archive = models.Archive.all().filter('yearmonth',src).fetch(10)
            # remove from archive
            if archive and archive[0]:
                archive = archive[0]
                archive.entrycount -= 1
                if archive.entrycount == 0:
                    archive.delete()
                else:
                    archive.put()

class NotFound(BaseRequestHandler):
    """Returns a Not Found page"""
    def get(self,error):
        self.generate('admin.html', {'content': '<h2>没有文章</h2>'})

       
class CategoriesPage(BaseRequestHandler):
    """/admin/categories - Admin page for categories."""
    @requires_admin(6)
    def get(self,comments={}):
        values = {
            'categories': models.Category.all()
        }
        values.update(comments)
        self.generate('categories.html', values)


class NewCategory(CategoriesPage):
    """/admin/categories/new - Create a new category"""
    @requires_admin(6)
    def post(self):
#        category_name = unicode(self.request.get('category_name').strip(),'utf-8') #Avoid white space categories
        category_name = self.request.get('category_name').strip()
        if not category_name:
            self.generate_js_error('输入的分类为空！')
        else:
            category_url = category_name.lower().replace(' ', '_')
            category_key = 'cat_' + category_url
            new_category = models.Category.get_by_key_name(category_key)
            if new_category:
                self.generate_js_error('该分类已存在！')
            else:
                new_category=models.Category(key_name=category_key, 
                                             category_name=category_name, 
                                             category_url=category_url)
                new_category.put()                        
                cache.delete_cache()
                memcache.delete("sidebardata")
                self.generate_js_action('Category created' , '' , 
                                        """new_cat('%s','%s');
                                        $('cat_form').reset();""" % (new_category.key(), category_name))


class DelCategory(BaseRequestHandler):
    """/admin/categories/del - Delete a category"""
    @requires_admin(6)
    def post(self):
        category_key = self.request.get('id')
        if not category_key:
            self.generate_js_error('没有选中任何分类！')
        else:
            try:
                category = models.Category.get(db.Key(category_key))
            except db.Error:
                self.generate_js_error('分类没有发现！')
                return
            if category is None:
                self.generate_js_error('分类没有发现！')
                return
            #Remove Category from posts
            cat_posts = models.Post.all().filter('categories',category)
            for post in cat_posts:
                post.categories.remove(category.key())
                post.put()
            #Remove the category
            category.delete()
            cache.delete_cache()
            memcache.delete("sidebardata")
            self.generate_js_action('删除分类！','', 
                             "$('%s').dispose();" % category_key)


class CommentsPage(BaseRequestHandler):
    """/admin/comments - List of comments"""
    @requires_admin(6)
    def get(self,errors={}):
           query = models.Comment.all().order('-date')
           #Pagination
           total_count = query.count()
           offset = self.request.get('offset')
           navigation = functions.navigation(offset,total_count)
           of = (navigation['current']-1)*10
           comments = query.fetch(limit=10,offset=of)
           values = {
               'comments': comments,
               'navigation': navigation
           }
           values.update(errors)
           self.generate('comments.html', values)


class DelComment(BaseRequestHandler):
    """/admin/comments/del - Delete a comment"""
    @requires_admin(6)
    def post(self):
        comment_key = self.request.get('id')
        if not comment_key:
            self.generate_js_error('不存在这条评论！')
        else:
            try:
                comment = models.Comment.get(db.Key(comment_key))
            except db.Error:
                self.generate_js_error('不存在这条评论！')
            if not comment:
                self.generate_js_error('不存在这条评论！')
            else:
                #delete the cached pages
                path =u'''post/'''+comment.post.permalink
                cache.delete_one_cache(path)
#                cache.delete_cache()
                #delete the post
                comment.delete()
                self.generate_js_action('已删除该条评论！','',
                                 "$('%s').dispose();" % comment_key)


class PostsPage(BaseRequestHandler):
    """/admin/posts - List of posts"""
    @requires_admin(6)
    def get(self, type='post',comments={}):
        query = models.Post.all().order('-created').filter('post_type', type)
        #Navigation
        total_count = query.count()
        offset = self.request.get('offset')
        navigation = functions.navigation(offset, total_count)
        of = (navigation['current']-1) * 10
        posts = query.fetch(limit=10, offset=of)
        values = {
            type + 's_list': 'yes',
            type: type,
            'type': type,
            'posts': posts,
            'navigation': navigation
        }
        values.update(comments)
        self.generate('posts.html', values)


class DelPost(BaseRequestHandler):
    """/admin/posts/del - Delete a post"""
    @requires_admin(6)
    def post(self, type='post'):
        post_key = self.request.get('id')
        if not post_key:
            self.generate_js_error(type + '没有发现')
        else:
            try:
                post = models.Post.get(db.Key(post_key))
            except db.Error:
                self.generate_js_error(type + '没有发现')
                return
            if not post:
                self.generate_js_error(type + '没有发现')
            else:
                #delete the comments from post
                for comment in models.Comment.gql('WHERE post=:1', post):
                    comment.delete()
                #delete the cached pages
                cache.delete_cache(post)
                if type=='page':
                    memcache.delete("sidebardata")
                #delete the post
                self.update_archive(post=post,value=None,new="del")
                post.delete()
                self.generate_js_action(type + '删除', '' , "$('%s').dispose();""" %  post_key)


class CreatePostPage(BaseRequestHandler):
    """/admin/posts/new - Create a new post or page"""
    @requires_admin(6)
    def get(self, type='post', err={}):
        cat =models.Category.all()
#        if cat.count() > 0:
        values = { 
                  'new_' + type: 'yes',
                  'type': type,
                  'action':'/admin/' + type + 's/new',
                  'post_categories': cat,
                  'title': 'Create New '+ type }
        values.update(err)
        self.generate('newpost.html', values)
#        else:
#            self.generate('admin.html', {'content': '<h2>最少先有一个分类才能写新文章哦！</h2><a href="/admin/categories/">去增加一个分类</a>'})
        
    @requires_admin(6)
    def post(self, type='post'):
        action, title,permalink, tags, tagsapp, excerpt, text, post_categories = (self.request.get(item) for item in ('action', 
                                                                                             'title',
                                                                                             'permalink',
                                                                                             'tags',
                                                                                             'tagsapp',
                                                                                             'excerpt', 
                                                                                             'text', 
                                                                                             'categories'))
        if not action=='Publish' and not action=='Save':
            self.generate_js_error('无效的数据！')
            return
        if not title:
            self.generate_js_error('输入标题！')
            return
        if not text:
            self.generate_js_error('输入正文！')
            return
#        if not permalink:
#            self.generate_js_error('permalink required')
#            return
        #Avoid invalid characters in permalink
        #TODO: Limit perpmalink to 40 characters && the permalink is unic
        if not permalink:
            permalink=title
        pattern = re.compile(u'[^\u4E00-\u9EA5a-zA-Z0-9_]')
        permalink = re.sub(pattern,'-',permalink.lower())
        #check if exist a post whith same permalink
        post = models.Post.get_by_key_name( type + '_' + permalink)
        if post:
            self.generate_js_error('该URL已存在')
            return
        post=models.Post(key_name= type + '_' + permalink, content=text, title=title , creator=users.get_current_user())
        if not excerpt:
            post.excerpt = re.sub("<.*?>","", text)[:300].strip().replace("\r","").replace("\n","<br/>")
        if post_categories:
            post.categories_keys=[db.Key(k) for k in post_categories.strip('+').split('+')]
        else:
            post.categories_keys=[]
        if len(post.categories_keys)==0:
            self.generate_js_error(u'请为文章增加一个分类！')
            return
        post.permalink = permalink
        msg =''
        if action=="Publish":
            post.draft = False
            post.published = datetime.datetime.now()
            if type=='page':
                memcache.delete("sidebardata")
            msg += "$('post_form_publish').setStyles({'display':'none'});"
        msg += """$('post_form').setProperty('action', '/admin/""" 
        msg += type + "s/edit');"
        if not self.request.get('comments_enabled'):
            post.comments_enabled = False
        post.post_type = type
        post.put()
        if not post.draft and type =='post':
            self.update_archive(post=post,value=None,new="new")
        post.set_tags_from_string(tags.replace(u"，",","),append=tagsapp)
        memcache.delete("sidebardata")
        cache.delete_cache()
        msg += """$('post_key').value = '%s';""" %  post.key()
        msg += """$('permalink').setProperty('disabled', 'disabled');"""
        self.generate_js_action(type + ' saved', '', msg)


class EditPostPage(CreatePostPage):
    """/admin/posts/edit - Edit a existing post"""
    @requires_admin(6)
    def get(self, type='post'):
        
        post_key = self.request.get('id')
        if not post_key:
            CreatePostPage.get(self, type, {'errordesc': '没有选中文章'})
        else:
            try:
                post = models.Post.get(db.Key(post_key))
                post.get_tags_as_string()
            except db.Error:
                CreatePostPage.get(self, type, {'errordesc': '无效的数据'})
                return
            if not post:
                CreatePostPage.get(self, type, {'errordesc': type + ' 不存在'})
            else:
                CreatePostPage.get(self, type, {
                                                'edit_' + type : 'yes',
                                                'post': post,
                                                'p_categories': '+'.join((str(cat.key()) for cat in post.categories if cat!=None)),
                                                'title': 'Edit Post',
                                                'action': '/admin/' + type + 's/edit',
                                                'key': post.key() ,
                                                'permalinknotedit': True ,
                                                })
    @requires_admin(6)
    def post(self, type='post'):
        post_key = self.request.get('key')
        if not post_key:
             self.generate_js_error('No ' + type +' selected')
        else: #get the post
            try:
                post = models.Post.get(db.Key(post_key))
            except db.Error:
                self.generate_js_error('Invalid data')
                return
            if not post:
                self.generate_js_error('Invalid ' + type)
                return
            action, title, tags,tagsapp, excerpt, text, post_categories = (self.request.get(item) for item in ('action', 'title', 'tags', 'tagsapp', 'excerpt', 'text', 'categories'))
            if not action=='Publish' and not action=='Save':
                self.generate_js_error('错误的动作')
                return
            if not title:
                self.generate_js_error('输入标题')
                return
            if not text:
                self.generate_js_error('输入正文！')
                return
            post.title,post.excerpt,post.content= title,excerpt,text
            msg = ''
            if post.draft == True:
                new ="new"
            else:
                new ="edit"
            if action=='Publish':
                post.draft = False
                post.published = datetime.datetime.now()
                msg = msg + "$('post_form_publish').setStyles({'display':'none'});"
            if post_categories:
                post.categories_keys=[db.Key(k) for k in post_categories.strip('+').split('+')]
            else:
                post.categories_keys=[]
            if len(post.categories_keys)==0:
                self.generate_js_error(u'必须有一个分类！')
                return
            if not excerpt:
                post.excerpt = re.sub("<.*?>","", text)[:300].strip().replace("\r","").replace("\n","<br/>")
            if not self.request.get('comments_enabled'):
                post.comments_enabled = False
            post.set_tags_from_string(tags.replace(u"，",","),append=tagsapp)
            post.put()
            if not post.draft and type =='post':
                self.update_archive(post=post,value=(models.Post.get(db.Key(post_key)).modified),new=new)
            memcache.delete("sidebardata")
            path =u'''post/'''+post.permalink
            cache.delete_one_cache(path)
            self.generate_js_action(type + ' saved', '', msg)


class Sidebar(BaseRequestHandler):
    """Pgae for set the components of the sidebar"""
    @requires_admin(6)
    def get(self):
        options = functions.get_options()
        opt = options.sidebar_widgets
        widgets = models.SidebarWidget.all()
        active_widgets = []
        inactive_widgets = []
        def get_name(key):
            for widget in widgets:
                if str(widget.key()) == key:
                    return widget.name
        #active widgets
        for item in opt:
            if item in ("categories" , "pages", "links", "feed","archives","tags","recentcomments"):
                active_widgets.append({'id':item , 'name': item, 'class': 'default'})
            else:
                active_widgets.append({'id':item , 'name': get_name(item), 'class': 'widget'})
        #check default items
        for item in ("categories" , "pages", "links", "feed","archives","tags","recentcomments"):
            if item not in opt:
                inactive_widgets.append({'id':item , 'name': item, 'class': 'default'})
        for widget in widgets:
            widget_key = str(widget.key())
            if widget_key not in opt:
                inactive_widgets.append({'id':widget_key , 'name': widget.name, 'class': 'widget'})
        values = { 'inactive': inactive_widgets, 'active': active_widgets}
        self.generate('sidebar.html', values)
        
    @requires_admin(6)
    def post(self):
        options = functions.get_options()
        errors = {}
        for name, value in self.request.params.items():
            errors.update(options.set_option(name, value))
        if errors:
            msg = ''
            for key in errors.keys():    
                msg = msg + ( "Growl.Error({title:'%s', text: '%s'});"  % (key, errors[key]) )
            self.generate_js(msg)  
        else:
            memcache.delete("sidebardata")
            memcache.delete("options")
            self.generate_js_action('Sidebar updated')


class LinksPage(BaseRequestHandler):
    """/admin/sidebr/links - List of links"""
    @requires_admin(6)
    def get(self):
        values = {
              'links': models.Link.all(),
              'form': models.LinkForm()
        }
        self.generate('links.html',values)


class NewLink(BaseRequestHandler):
    """/admin/sidebar/links/new - Create a new link"""
    @requires_admin(6)
    def post(self):
        data = models.LinkForm(data=self.request.POST)
        if not data.is_valid():
            msg=''
            for key in data.errors.keys():
                msg=msg+ "Growl.Error({title:'%s', text: '%s'});" % (key, data.errors[key])
            self.generate_js(msg)
            return
        new_link = data.save()
        cache.delete_cache()
        memcache.delete("sidebardata")
        
        self.generate_js_action('Link created', '',"""new_link('%s','%s','%s');$('link_form').reset();""" % ( new_link.key() , new_link.name, new_link.link ))


class DelLink(BaseRequestHandler):
    """/admin/sidebar/links/del - Delete a link"""
    @requires_admin(6)
    def post(self):
        link_key = self.request.get('id')
        if not link_key:
            self.generate_js_error('链接没有被选中')
        else:
            try:
                link = models.Link.get(db.Key(link_key))
            except db.Error:
                self.generate_js_error('链接没有被发现')
                return
            if link is None:
                self.generate_js_error('链接没有被发现')
                return
            link.delete()
            cache.delete_cache()
            memcache.delete("sidebardata")
            self.generate_js_action('Link deleted','',"$('%s').dispose();" % link_key)


class OptionsPage(BaseRequestHandler):
    """/admin/options - list of options"""
    @requires_admin(6)
    def get(self):
        options=models.Option.all().filter('space', 'global')
        values = {'global_options': options,
#                  'user':','.join(options.get().permission) 
                  }
        self.generate('options.html', values )
        
    @requires_admin(6)
    def post(self):
        options = functions.get_options()
        global_options = models.Option.all().filter('space', 'global')
        options_ok = []
        errors = {}
        for name, value in self.request.params.items():
            if name =='permission':
                value =str([ss.strip() for ss in value.split(',') if len(ss) > 0 and ss.find("@")>-1])
            errors.update(options.set_option(name, value))
            options_ok.append(name)
        for opt in global_options:
            if opt.option_type == "boolean" and opt.name not in options_ok:
                errors.update(options.set_option(opt.name, "False"))
        if errors:
            msg = ''
            for key in errors.keys():    
                msg = msg + ( "Growl.Error({title:'%s', text: '%s'});"  % (key, errors[key]) )
            self.generate_js(msg)  
        else:
            memcache.delete("options")
            cache.delete_cache()
            self.generate_js_action('选项被保存')  


class WidgetPage(BaseRequestHandler):
    """/admin/sidebar/widgets - list of wigetss"""
    @requires_admin(6)
    def get(self):
        values = {
              'widgets': models.SidebarWidget.all(),
              'form': models.SidebarWidgetForm()
        }
        self.generate('widgets.html',values)        


class NewWidget(BaseRequestHandler):
    """/admin/sidebar/widgets/new - Create a new widget"""
    @requires_admin(6)
    def post(self):
        data = models.SidebarWidgetForm(data=self.request.POST)
        if not data.is_valid():
            msg=''
            for key in data.errors.keys():
                msg=msg+ "Growl.Error({title:'%s', text: '%s'});" % (key, data.errors[key])
            self.generate_js(msg)
            return
        new_widget = data.save()
        title = new_widget.title
        if not title:
            title = ''
        new_widget.put()
        self.generate_js_action('挂件被创建','',"""
                            new_widget('%s','%s','%s', '%s');
                            """ % (new_widget.key() , new_widget.name, title, cgi.escape(new_widget.text).replace('\n','<br />')  ))


class DelWidget(BaseRequestHandler):
    """/admin/sidebar/widgets/del - Delete a widget"""
    @requires_admin(6)
    def post(self):
        widget_key = self.request.get('id')
        if not widget_key:
            self.generate_js_error('不存在该挂件')
        else:
            try:
                widget = models.SidebarWidget.get(db.Key(widget_key))
            except db.Error:
                self.generate_js_error('不存在该挂件')
                return
            if widget is None:
                self.generate_js_error('不存在该挂件')
                return
            widget.delete()
            cache.delete_cache()
            #memcache.delete("sidebar")
            self.generate_js_action('删除挂件','' ,"$('%s').dispose();" % widget_key)


class EditWidget(BaseRequestHandler):
    """/admin/sidebar/widget/edit - edit a widget"""
    @requires_admin(6)
    def post(self):
        widget_key = self.request.get('id')
        if not widget_key:
            self.generate_js_error('不存在该挂件')
        else:
            try:
                widget = models.SidebarWidget.get(db.Key(widget_key))
            except db.Error:
                self.generate_js_error('不存在该挂件')
                return
            if widget is None:
                self.generate_js_error('不存在该挂件')
                return
            data = models.SidebarWidgetForm(data=self.request.POST, instance=widget)
            if not data.is_valid():
                msg=''
                for key in data.errors.keys():
                    msg=msg+ "Growl.Error({title:'%s', text: '%s'});" % (key, data.errors[key])
                self.generate_js(msg)
                return
            new_widget = data.save()
            title = new_widget.title
            if not title:
                title = ''
            self.generate_js("""Growl.Action({title:'%s'});
                                replace_widget('%s','%s','%s', '%s');
                                $('widget_form').reset();""" % ('Widget modified', new_widget.key() , new_widget.name, title, cgi.escape(new_widget.text).replace('\n','<br />')  ))


class ClearCache(BaseRequestHandler):
    """/admin/cache/del - Clear the cached pages"""
    @requires_admin(6)
    def post(self):
        cache.delete_cache()
        self.generate_js_action('缓存被清除',extra="location.reload();")


class CheckOptions(BaseRequestHandler):
    """/admin/options/check - Checks if the defaults options are created"""
    @requires_admin(6)
    def post(self):
        options = functions.get_options()
        options.set_defaults(False)
        self.generate_js_action('选项更新成功')


class MainAdminPage(BaseRequestHandler):
    """/admin/ - main admin page"""
    @requires_admin(6)
    def get(self):
        self.generate('admin.html',{})

class FileManager(BaseRequestHandler):
    """/admin/filemanager - filemanager page"""
    @requires_admin(6)
    def get(self):
        self.current_page = "upload"
        
#        files = models.UploadFile.all().order('-date').fetch(1000)
#        for file in files:
#            dir ="/myfile"
#            filesystem.Files(key_name=dir+"/"+file.orig_name,
#                             basename=file.orig_name,
#                             ctime_dt=datetime.datetime.now(),
#                             mtime_dt=datetime.datetime.now(),
#                             dir=dir,
#                             path=dir+"/"+file.orig_name,
#                             content = file.data,
#                             filetype =file.ext).put()              
        newfiles = filesystem.Files.all().order('-mtime_dt').fetch(1000)    
        values = {
            'files' : newfiles,
            'filemanager': True,
        }
        self.generate('filemanager.html',values)
        
    @requires_admin(6)
    def post(self): # delete files
        delids = self.request.POST.getall('del')
        if delids:
            for id in delids:
                newfile = filesystem.Files.get_by_key_name(id)
                newfile.delete()
        self.redirect('/admin/filemanager')

class CodeManager(BaseRequestHandler):
    """/admin/filemanager - filemanager page"""
    @requires_admin(6)
    def get(self):
        self.current_page = "upload"
        files = models.Code.all().order('-date')
        values = {
            'files' : files,
            'codemanager': True,
        }
        self.generate('codemanager.html',values)
        
    @requires_admin(6)
    def post(self): # delete files
        delids = self.request.POST.getall('del')
        actives =self.request.POST.getall('act')
        acs=[models.Code.get_by_id(int(id)).orig_name for id in actives]
        codes = models.Code.all().fetch(1000)
        for c in codes:
            if acs.count(c.orig_name)>0:
                if not c.active:
                    c.active=True
                    c.put()
            else:
                if c.active:
                    c.active=False
                    c.put()
        if delids:
            for id in delids:
                file = models.Code.get_by_id(int(id))
                file.delete()
        self.redirect('/admin/codemanager')
                    
class Upload(BaseRequestHandler):
    @requires_admin(6)
    def post(self):
        filename = self.param('filename')
        data = self.param('upfile')
        fileext = self.param('fileext')
        if not filename:
            self.generate_js_error('没有选中文件')
            self.redirect('/admin/filemanager')
        elif len(data)>1000000:
            self.generate_js_error('文件太大了')
            self.redirect('/admin/filemanager')
        else:
#            models.UploadFile(key_name = filename,orig_name = filename, ext = fileext, data = data).put()
            dir ="/myfile/upload"
            filesystem.Files(key_name=dir+"/"+filename,
                             basename=filename,
                             ctime_dt=datetime.datetime.now(),
                             mtime_dt=datetime.datetime.now(),
                             dir=dir,
                             path=dir+"/"+filename,
                             content = data,
                             filetype =fileext).put()

            self.redirect('/admin/filemanager')

class CachePage(BaseRequestHandler):
    """/admin/options/cache - list of wigetss"""
    @requires_admin(6)
    def get(self):
        values = {
              'cached_pages': models.CachedPage.all()
        }
        self.generate('cache.html',values)     

class DelCache(BaseRequestHandler):
    """/admin/categories/del - Delete a category"""
    @requires_admin(6)
    def post(self):
        path = self.request.get('id')
        if not path:
            self.generate_js_error('文件没有被选中')
        else:
            try:
                cached_page = models.CachedPage.get(db.Key(path))
#                cached_page = models.CachedPage.get_by_key_name(path)
            except db.Error:
                self.generate_js_error('文件没有被选中')
                return
            if cached_page is None:
                self.generate_js_error('文件没有被选中')
                return
            #Remove Category from posts
                   
            cached_page.delete()
            memcache.delete("sidebardata")
            self.generate_js_action('缓存被删除','', 
                             "$('%s').dispose();" % path)
                    
class UploadCode(BaseRequestHandler):
    @requires_admin(6)
    def post(self):
        filename = self.param('filename')
        data = self.param('upfile')
        if not filename:
            self.generate_js_error('not select a file!')
            self.redirect('/admin/codemanager')
        elif len(data)>1000000:
            self.generate_js_error('file is too large!')
            self.redirect('/admin/codemanager')
        else:
            models.Code(orig_name = filename, user = users.GetCurrentUser(), data = data).put()
            self.redirect('/admin/codemanager')
                        
def main():
    options = functions.get_options()
    users.level = 0
    if users.get_current_user():
        users.level = 3
        if users.is_current_user_admin() or options.permission.count(users.get_current_user().email()) > 0:
            users.level = 6
            if users.is_current_user_admin():
                users.level = 9
    application = webstart.WSGIApplication2([(r'/admin/(post|page)s/',PostsPage),
                                        ('/admin/categories/new',NewCategory),
                                        ('/admin/categories/del',DelCategory),
                                        ('/admin/categories/',CategoriesPage),
                                        (r'/admin/(post|page)s/new',CreatePostPage),
                                        (r'/admin/(post|page)s/del',DelPost),
                                        (r'/admin/(post|page)s/edit',EditPostPage),
                                        ('/admin/comments/',CommentsPage),
                                        ('/admin/comments/del',DelComment),
                                        ('/admin/upload', Upload),
                                        ('/admin/uploadcode', UploadCode),
                                        ('/admin/filemanager', FileManager),
                                        ('/admin/codemanager', CodeManager),
                                        ('/admin/sidebar/',Sidebar),
                                        ('/admin/sidebar/links/',LinksPage),
                                        ('/admin/sidebar/links/new',NewLink),
                                        ('/admin/sidebar/links/del',DelLink),
                                        ('/admin/sidebar/widgets/',WidgetPage),
                                        ('/admin/sidebar/widgets/new',NewWidget),
                                        ('/admin/sidebar/widgets/del',DelWidget),
                                        ('/admin/sidebar/widgets/edit',EditWidget),
                                        ('/admin/options/', OptionsPage),
                                        ('/admin/options/cache/', CachePage),
                                        ('/admin/options/cache/del', DelCache),
                                        ('/admin/options/check', CheckOptions),
                                        ('/admin/cache/del', ClearCache),
                                        ('/admin/', MainAdminPage),
                                        ('/admin/(.*)',NotFound)],
                                        debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()